var express = require('express');
var app = express();

app.set('view engine','ejs');


app.get('/', function (req, res) {
    res.render('home.ejs');
});


app.get('/parse', function(req, res) {
    var originalHex = req.query.hex;
    var dataVisualization = parseUDPPacket(originalHex);
    res.json(dataVisualization);
});


function parseUDPPacket(parcketText) {
    var dataVisualization = new Array;

    var index = parcketText.toLowerCase().indexOf("7e23");

    if (index == -1) {
        dataVisualization[0] = {"错误": "找不到开始符，不是一个互动包"};
        return dataVisualization;
    }

    var packetHex = parcketText.substring(index);

    


    // var dataBinary = new Buffer(originalBase64, 'base64');

    var dataBinary = new Buffer(packetHex, 'hex');

    var dataString = dataBinary.toString();

    var startSymbol = dataBinary.slice(0, 2);

    if (startSymbol.toString() === "~#") {
        dataVisualization[0] = {"startSymbol": "开始符『~#』正确，是一个UDP互动包"};
    } else {
        dataVisualization[0] = {"startSymbol": "开始符错误，不是一个UDP互动包"};
    }

    var syncCode = dataBinary.slice(2, 6).readUIntBE(0, 4);

    dataVisualization[1] = {"SYN/ACK": syncCode};


    var deviceIdentifier = dataBinary.slice(6,38).toString();
    dataVisualization[2] = {"设备标识符": deviceIdentifier};


    var commandType = dataBinary.slice(38,39).readUIntBE(0, 1);

    dataVisualization[3] = {"指令类型": "0x" + commandType.toString(16).toUpperCase(), "指令列表": "0x01匹配（应答0x81），0x02按键（应答0x82），0x03输入法（应答0x83），0x04传感器（应答0x84），0x05鼠标（应答0x85），0x06切屏（应答0x86），0x07拉屏（应答0x87），0x08触屏（应答0x88），0x09显示设备信息（应答0x89），0x0A新匹配（应答0x8A）"};

    var payloadLength = dataBinary.slice(39, 43).readUIntBE(0, 4);

    dataVisualization[4] = {"指令长度": payloadLength};

    var commandData = dataBinary.slice(43, 43 + payloadLength);

    if (payloadLength == 4) {
        dataVisualization[5] = {"指令数据": commandData.readUIntBE(0, 4)};
    } else {
        dataVisualization[5] = {"指令数据": JSON.parse(commandData.toString())};
    }

    var checkCode =  dataBinary.slice(43 + payloadLength, 44 + payloadLength).readUIntBE(0, 1);

    dataVisualization[6] = {"校验位": checkCode};

    dataVisualization[7] = {"原始数据": parcketText};

    return dataVisualization;
}

app.listen(9600, function () {
    console.log('Example app listening on port 9600!');
});